package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class RoleServiceimpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 分页查询角色信息
     *
     * @param roleDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResponse<RoleVo> querPage(RoleDto roleDto, Integer pageNum, Integer pageSize) {
        Role role = new Role();
        BeanUtil.copyProperties(roleDto, role);
        PageHelper.startPage(pageNum, pageSize);
        Page<Role> page = roleMapper.querPage(role);
        return PageResponse.of(page, RoleVo.class);
    }

    /**
     * 角色添加
     * @param roleDto
     */
    @Override
    public void addRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.addRole(role);
    }

    /**
     * 根据角色查询选中的资源数据
     * @param roleId
     * @return
     */
    @Override
    public List<String> findCheckedResources(Long roleId) {
       List<String> list = roleMapper.findCheckedResources(roleId);
        return list;
    }

    /**
     * 角色修改+启用禁用
     * @param roleDto
     */
    @Override
    public void updateRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);

        //TODO 该角色是否绑定用户---有绑定就不能更新和禁用

        // 角色修改+启用禁用
        roleMapper.updateRole(role);
        //如果CheckedResourceNos为空直接返回
        if(ObjectUtil.isEmpty(roleDto.getCheckedResourceNos())){
            return;
        }

        // 删除角色资源关联表数据---------------先删除，在添加
        roleMapper.deleteRoleResource(role.getId());
        // 添加角色资源关联表数据
        String[] checkedResourceNos = roleDto.getCheckedResourceNos();
        List<String> list = Arrays.asList(checkedResourceNos);//将数组转换为集合
        ArrayList<RoleResource> roleResources = new ArrayList<>();
        for (String s:list){
            RoleResource roleResource = new RoleResource();
            roleResource.setRoleId(role.getId());
            roleResource.setResourceNo(s);
            roleResources.add(roleResource);
        }
        // 批量添加角色资源关联表数据
        roleMapper.batchInsert(roleResources);

    }

    /**
     * 角色删除
     * @param roleId
     */
    @Override
    public void deleteRole(Long roleId) {
        roleMapper.deleteRole(roleId);
    }

    /**
     * 角色下拉框
     * @return
     */
    @Override
    public List<RoleVo> roleDropdownMenu() {
        return roleMapper.roleDropdownMenu();
    }
}
